package com.hy.dao.impl;

import com.hy.bean.Deptfunds;
import com.hy.dao.DeptfundsDao;
import com.hy.utils.DBManager;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

public class DeptfundsDaoImpl implements DeptfundsDao {
    private QueryRunner qr = new QueryRunner();
    @Override
    public List<Map<String, Object>> selectAll(String deptName) throws Exception {
        Connection conn = DBManager.getConnection();

        String sql = "select d.*,dept.*,c.username from deptfunds d \n" +
                "inner join department dept \n" +
                "on d.dept_id = dept.id\n" +
                "inner join consumer c \n" +
                "on d.czr = c.id where dept.dept_name like ?";

        List<Map<String, Object>> list = qr.query(conn, sql, new MapListHandler(), "%"+deptName+"%");

        DbUtils.close(conn);

        return list;
    }

    @Override
    public List<Map<String, Object>> selectDeptAll(Integer deptId) throws Exception {
        Connection conn = DBManager.getConnection();

        String sql = "select c.username,pa.apply_time,g.goodsname,p.goods_count,p.money from purchase_apply pa \n" +
                "inner join purchase_apply_detail p\n" +
                "on pa.id = p.purchase_apply_id\n" +
                "inner join consumer c\n" +
                "on pa.consumer_id = c.id\n" +
                "inner join goods g\n" +
                "on g.id = p.goods_id\n" +
                "where pa.dept_id = ? and status = '2'";

        List<Map<String, Object>> list = qr.query(conn, sql, new MapListHandler(),deptId);

        DbUtils.close(conn);
        return list;
    }

    @Override
    public Boolean updateDeptBalanceMinus(Connection conn, BigDecimal deptId, BigDecimal balance) throws Exception {
        // 更新部门余额
        String sql = "update deptfunds set balance = balance - ? where dept_id = ?";

        int i = qr.update(conn, sql, balance, deptId);

        return i > 0;
    }

    @Override
    public Boolean updateDeptBalanceAdd(int deptId, Double balance) throws Exception {
        Connection conn = DBManager.getConnection();

        String sql = "update deptfunds set balance = balance + ? where dept_id = ?";

        int i = qr.update(conn, sql, balance, deptId);

        DbUtils.close(conn);

        return i > 0;
    }

    @Override
    public Boolean deleteById(int deptId) throws Exception {
        Connection conn = DBManager.getConnection();

        String sql = "delete from deptfunds where dept_id = ?";

        int i = qr.update(conn, sql, deptId);

        DbUtils.close(conn);

        return i > 0;
    }


}
